package com.jdrx.sw.sewage.common.util;

import com.jdrx.platform.commons.rest.beans.enums.EApiStatus;
import com.jdrx.platform.commons.rest.beans.vo.ResposeHelperVO;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.platform.commons.rest.utils.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.Objects;


/**
 * 处理远程调用结果
 * <p>
 *
 */
public class ResponseUtils {
    private final static Logger logger = LoggerFactory.getLogger(ResponseUtils.class);

    private final static String WAPPER_FAIL = "";

    private final static String WAPPER_ERROR = "远程接口无法处理请求, err: %s ";

    public static <T> T execAndGetData(Call<ResposeHelperVO<Object>> call) throws BizException {
        try {
            Response<ResposeHelperVO<Object>> resp = call.execute();
            return checkRespAndGetData(resp);
        } catch (IOException e){
            logger.error("远程调用失败", e);
            throw new BizException("远程调用失败");
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T checkRespAndGetData(Response<ResposeHelperVO<Object>> resp) throws BizException {
        if (!resp.isSuccessful()) {
            logger.error("远程调用接口失败，err_code:{} , err_message:{}", resp.code(), resp.message());
            throw new BizException(String.format("远程调用接口失败, err_code:%s", resp.code()));
        }
        ResposeHelperVO<Object> body = resp.body();

        if (Objects.isNull(body)) {
            logger.error("远程接口无数据返回");
            throw new BizException("远程接口无数据返回");
        }
        if (!Objects.equals(body.getStatus(), EApiStatus.SUCCESS.getStatus())) {
            logger.error("远程接口无法处理请求，errBody:{}", JsonMapper.toJsonString(body));
            throw new BizException(String.format("远程接口无法处理请求, err: %s ", body.getMessage()));
        }

        Object data = body.getData();
        logger.debug("获取到数据，body:'{}'", data);
        T obj;
        try {
            obj = (T) data;
        } catch (Exception e) {
            logger.error("无法解析数据",e);
            throw new BizException("解析远程数据失败");
        }
        return obj;
    }

}